package com.lagou.gateway.filter.factory;

import com.lagou.gateway.BaseResponseBodyEntity;
import com.lagou.gateway.ResponseCodeEnum;
import com.lagou.gateway.util.ResponseBodyUtil;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;

import java.util.function.Function;
import java.util.function.Predicate;

public abstract class AbstractVerificationFilterFactory<T>
        extends AbstractGatewayFilterFactory<T> {
    public AbstractVerificationFilterFactory(Class<T> configClass) {
        super(configClass);
    }
    private Function<ServerHttpRequest,ServerHttpRequest> buildRequest;


    protected abstract Predicate<ServerHttpRequest> requestPredicate(T config);
    protected void setBuildRequest(Function<ServerHttpRequest,ServerHttpRequest> function){
        this.buildRequest = function;
    }
    @Override
    public GatewayFilter apply(T config) {
        return ((exchange, chain) -> {
            Boolean result = requestPredicate(config).test(exchange.getRequest());
            if(result){
                if(buildRequest != null) {
                    ServerHttpRequest request = buildRequest.apply(exchange.getRequest());
                    return chain.filter(exchange.mutate().request(request).build());
                }else {
                    return chain.filter(exchange);
                }
            }

            ServerHttpResponse response = exchange.getResponse();
            HttpHeaders httpHeaders = response.getHeaders();
            httpHeaders.add("Content-Type", "application/json; charset=UTF-8");
            BaseResponseBodyEntity entity
                    = new BaseResponseBodyEntity(ResponseCodeEnum.UNAUTHORIZED, "unauthorized");

            return ResponseBodyUtil.writeBuffer(exchange.getResponse(),entity);
        });
    }
}
